<?php

/**
 * DB类 Yjnic_Db_Execute
 *
 * @author prettyyjnic <prettyyjnic@qq.com> 20151027
 */
class Yjnic_Db_Execute {

    protected $_pdo_ins = NULL;
    protected $_exec_id = FALSE;
    protected $_debug = FALSE;
    protected $_last_sql = '';
    protected $_params = array();

    public function __construct(PDO $pdo, $debug = FALSE){
        $this->_pdo_ins = $pdo;
        $this->_debug = $debug;
    }

    /**
     * @param 执行一条 SQL 语句，并返回受影响的行数
     */
    public function execute($sql, $params=array()){
        $this->_last_sql = $sql;
        $this->_exec_id = $this->_pdo_ins->prepare($sql);        
        if (empty($params)) {    
            $params = $this->_params;
        }
        $result = $this->_exec_id->execute($params);
        $this->_params = array();
        if ($result) {
            if (stripos($sql, 'INSERT')===false) {
                // echo 999;
                return $this->_exec_id->rowCount();//影响的行数
            }else{
                return $this->_pdo_ins->lastInsertId();//影响的行数
            }
        }else{
            if ($this->_debug) {
                throw new Yjnic_Db_Exception("Execute Exception, sql:". $this->_last_sql, 504);
            }else{
                throw new Yjnic_Db_Exception("DB ERROR:". $this->_last_sql, 504);
            }
        }
    }

    /**
     * 插入一条数据
     * @param $data 要插入的数据 array('key'=>value) key是字段名称,value是要插入的字段内容
     * @param $table 表名称
     * @return numner 0或者自增ID值
     */
    public function insert($data, $table){
        if (empty($data) || empty($table)) {
            if ($this->_debug) {
                throw new Yjnic_Db_Exception("Empty Data Or Table:", 504);
            }else{
                throw new Yjnic_Db_Exception("DB ERROR:", 504);
            }         
        }
        $sql = $this->_parseInsertSql($data, $table);
        return $this->execute($sql);       
    }


    /**
     * 修改一条数据
     * @param $data  要修改的数据 array('key'=>value) key是字段名称,value是要插入的字段内容
     * @param $where  修改条件
     * @param $table  表名称
     * @return true/FALSE 成功或者失败
     */
    public function update($data, $where, $table) {
        if (empty($where) || empty($table)) {
            if ($this->_debug) {
                throw new Yjnic_Db_Exception("Empty Where Or Table:", 504);
            }else{
                throw new Yjnic_Db_Exception("DB ERROR:", 504);
            }         
        }
        $where = $this->_parseWhere($where);
        $sql = $this->_parseUpdateSql($data, $where, $table);
        return $this->execute($sql, $this->_params);
    }


    /**
     * 删除一条数据
     * @param $where  删除条件
     * @param $table  表名称
     * @return true/FALSE 成功或者失败
     */
    public function delete($where, $table) {
        if (empty($where) || empty($table)) {
            if ($this->_debug) {
                throw new Yjnic_Db_Exception("Empty Where Or Table:", 504);
            }else{
                throw new Yjnic_Db_Exception("DB ERROR:", 504);
            }         
        }
        $where = $this->_parseWhere($where);
        $sql = $this->_parseDeleteSql($where, $table);
        return $this->execute($sql, $this->_params);
    }

    /**
     *  get last sql
     */
    public function getLastSql(){
        return $this->_last_sql;
    }

     protected function _parseInsertSql($data, $table){       
        $keys = array();
        $values = array();
        foreach ($data as $k => $v) {
            $keys[] = '`'.$k.'`';
            $values[] = $this->_pdo_ins->quote($v); 
        }
        $sql = "INSERT INTO `{$table}` (".implode(',', $keys).") VALUES (".implode(',', $values).");";
        return $sql;
    }

    protected function _parseUpdateSql($data, $where=FALSE, $table){
        
        $field_values = array();
        foreach ($data as $k => $v) {
           $field_values[] = '`'.$k.'` = '. $this->_pdo_ins->quote($v);
        }
        $sql = "UPDATE `{$table}` SET ".implode(',', $field_values)." WHERE {$where};";
        return $sql;
    }

    protected function _parseDeleteSql($where=FALSE, $table){       
        $sql = "DELETE FROM `{$table}` WHERE {$where}";
        return $sql;
    }

    /**
     * @param mix $map
     * $map 如果是字符串直接返回字符串，如果是数组则将array[1] 添加到 $this->_params，返回array[0]
     */
    protected function _parseWhere($map){
        if ($map === TRUE) {
            return 1;
        }
        if (is_array($map)) {
            $this->_params = array_merge($this->_params, array_values($map[1]));
            return $map[0];
        }else{//string
            return $map;
        }
    }
}
